﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CompareDuplicate.aspx.cs" Inherits="CRMWeb.Pages.Contact.CompareDuplicate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Duplicate Client Detection</title>
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <style type="text/css">
        table, td, tr
        {
            border: 1px solid black;
            border-collapse: collapse;
        }
       
    </style>
</head>
<script type="text/javascript">
    var currentClientID = getQuerystring('contact_id', '');
    var dropdownlist = new Object();
    var selectedApplication = '';
     
    function getQuerystring(key, defaultValue) {
        if (defaultValue == null) defaultValue = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return defaultValue;
        else {
            return qs[1];
        }
    }
    //window.onunload = function refreshParent() {
    //    window.opener.location.reload();
    //}
    function saveApplicationHistory(app_id) {
        var todaydate = new Date();
        var month = todaydate.getMonth() + 1;
        var hdate = month + '/' + todaydate.getDate() + '/' + todaydate.getFullYear();
        var hdesc = "Application " + app_id + " Deleted";
        var htime = todaydate.getHours() + ':' + todaydate.getMinutes() + ':' + todaydate.getSeconds();
        $.ajax({
            url: '/WebServices/History.ashx?method=saveNewHistory',
            contentType: "application/json; charset=utf-8",
            data: {
                'HistoryType': 'Application', 'contactid': '0', 'hdate': hdate, 'htime': htime, 'action': 'Application Deleted (Detective) ',
                'user': $('#hdnUserName').val(), 'description': hdesc, 'appid': app_id
            },
            success: function () {
            }
        });
    }
    function saveContactHistory(contactId,dupwithContact) {
      
        var todaydate = new Date();
        var hdate =  todaydate.getMonth() + 1 + '/' + todaydate.getDate() + '/' + todaydate.getFullYear();
        var hdesc = ' Remove the duplicated client= ' +contactId  + ',to new client=' +dupwithContact ;
        var htime = todaydate.getHours() + ':' + todaydate.getMinutes() + ':' + todaydate.getSeconds();
       
        // insert history record for Current Client
        $.ajax({
            url: '/WebServices/History.ashx?method=saveNewHistory',
            data: {
                'HistoryType': 'Contact', 'contactid': contactId, 'hdate': hdate,
                'htime': htime, 'action': 'Remove Duplicated (Detective)', 'user': $('#hdnUserName').val(), 'description': hdesc, 'appid': '0'
            },
            success: function () {
            }
        });
        // insert history record for Duplicate Client
        $.ajax({
            url: '/WebServices/History.ashx?method=saveNewHistory',
            data: {
                'HistoryType': 'Contact', 'contactid': dupwithContact, 'hdate': hdate,
                'htime': htime, 'action': 'Remove Duplicated (Detective)', 'user': $('#hdnUserName').val(), 'description': hdesc, 'app_id': '0'
            },
            success: function () {
            }
        });
    }
    function removeDups(origArr) {
        var newArr = [],
        origLen = origArr.length,
        found,
        x, y;

        for (x = 0; x < origLen; x++) {
            found = undefined;
            for (y = 0; y < newArr.length; y++) {
                if (origArr[x] === newArr[y]) {
                    found = true;
                    break;
                }
            }
            if (!found) newArr.push(origArr[x]);
        }
        return newArr;
    }
    function CheckValidOperation(grpvalue) {
        var count = 0;
        var isvalidOpration = false;
        for (j = 0; j < grpvalue.length; j++)
        {
            var inputcmb = document.getElementsByTagName("select");
            for (i = 0; i <= inputcmb.length - 1; i++) {
                cmbname = inputcmb[i].getAttribute('id');
                if (cmbname.indexOf("cmbgrp") == 0) {
                    $('#hdnClientID').val(cmbname.replace('cmbgrp', ''));
                    if ($('#' + cmbname).val() === grpvalue[j]) {
                        if ($('#cmbClientAction' + $('#hdnClientID').val()).val() == "Keep") {
                            count = count + 1;
                        }
                    }
                }
            }
            if (count == 1) {
                isvalidOpration = true;
                count = 0;
            }
            else if (count > 1) {
                $.messager.alert('Morgan CRM', 'Group :' +  grpvalue[j] + ' Only ONE Keep per Group allow ! ');
                isvalidOpration = false;
                break;
            }
            else if (count < 1) {
                $.messager.alert('Morgan CRM', 'Group :' + grpvalue[j] + ' Atleast ONE Keep per Group required ! ');
                isvalidOpration = false;
                break;
            }
        }
        return isvalidOpration;
    }
    function saveChanges() {
        $('#lnksave').linkbutton('disable');
        var ClientsToDelete = '';
        var ClientToKeep = '';
        var deletedClient = '';
        var grpvalue = new Array();
        var keepCount = 0;
        var inputcombo = $('select');
        for (x = 0; x <= inputcombo.length - 1; x++) {
            myname = inputcombo[x].getAttribute('id');
            if (myname.indexOf("cmbgrp") == 0) {
                grpvalue.push($('#' + myname).val());
            }
            else if (myname.indexOf("cmbDelApp") == 0) {

                if ($('#cmbClientAction' + myname.replace('cmbgrp', '')).val() == "Keep")
                    selectedApplication += $('#' + myname).combogrid('getText');
            }
        }
        grpvalue = removeDups(grpvalue);
        // check Operation is valid or out
        var validOP = CheckValidOperation(grpvalue);
        if (validOP == true) {
            for (j = 0; j < grpvalue.length; j++) {
                var inputcmb = document.getElementsByTagName("select");
                for (i = 0; i <= inputcmb.length - 1; i++) {
                    cmbname = inputcmb[i].getAttribute('id');
                    if (cmbname.indexOf("cmbgrp") == 0) {
                        $('#hdnClientID').val(cmbname.replace('cmbgrp', ''));
                        if ($('#' + cmbname).val() === grpvalue[j]) {
                            if ($('#cmbClientAction' + $('#hdnClientID').val()).val() == "Keep")
                                ClientToKeep = $('#hdnClientID').val();
                            else if ($('#cmbClientAction' + $('#hdnClientID').val()).val() == "Delete")
                                ClientsToDelete += $('#hdnClientID').val() + ',';
                        }
                    }
                }
                ClientsToDelete = ClientsToDelete.replace(/,,*/g, ',');
                ClientsToDelete = ClientsToDelete.replace(/,$/, '');
                ClientsToDelete = ClientsToDelete.replace(/^,/, '');
                deletedClient += ClientsToDelete + ',';
                var arrDuplicateClient = new Array();
                arrDuplicateClient = ClientsToDelete.split(',');
                if (ClientsToDelete != '') {
                    $.ajax({
                        url: '/WebServices/DuplicateContactDetective.ashx?method=DuplicateMultipleClient',
                        data: { clients: ClientsToDelete, duplicateWith: ClientToKeep },
                        success: function () {

                        }
                    });
                    for (var i = 0; i < arrDuplicateClient.length ; i++) {
                        saveContactHistory(arrDuplicateClient[i], ClientToKeep);
                    }
                }
                ClientsToDelete = '';
                ClientToKeep = '';
            }
            // Delete selected Applications
            var del_application = '';
            var inputcmb = document.getElementsByTagName("select");
            for (i = 0; i <= inputcmb.length - 1; i++) {
                cmbname = inputcmb[i].getAttribute('id');
                if (cmbname.indexOf("cmbDelApp") == 0) {
                    if ($('#' + cmbname).combogrid('getText') != '')
                        del_application += $('#' + cmbname).combogrid('getText') + ',';
                }
            }
            del_application = del_application.replace(/,,*/g, ',');
            del_application = del_application.replace(/,$/, '');
            del_application = del_application.replace(/^,/, '');
            deleteApplications(del_application);
            $('#lnksave').linkbutton('enable');
            $.messager.confirm('Morgan CRM', ' Clients : <b>' + deletedClient + ' </b> duplicated Successfully </br> Do you want to refresh Data ?', function (r) {
                if (r == true) {
                    window.location.reload();
                }
            });
        }
        window.opener.location.reload();
    }
    function deleteApplications(app_list) {
        
        var arrApplicationDel = app_list.split(',');
        if (app_list != '') {
            $.ajax({
                url: '/WebServices/DuplicateContactDetective.ashx?method=DeleteMultipleApplication',
                contentType: "application/json; charset=utf-8",
                data: { applications: app_list },
                success: function (data) {
                    for (var j = 0; j < arrApplicationDel.length; j++) {
                       
                         saveApplicationHistory(arrApplicationDel[j]);
                    }
                }
            });
        }
    }
    window.onresize = function () {
        $('#pnlCompareDuplicate').panel('resize', {
            width: window.innerWidth,
            height: window.innerHeight
        });
        $('#dgCompareDuplicate').datagrid('resize', {
            width: window.innerWidth - 10
        });
    }
    function openApplicationForm(appid) {
        window.open("/pages/Application_Form.aspx?verified=0&id=" + appid, "_blank");
    }
    function ViewApp(ctrlid) {  
        var selectedApp = $('#cmbViewApp' + ctrlid).val();
        window.open("/Pages/Application/ApplicationDetail.aspx?app_id=" + selectedApp.trim(), "_blank");
    }
    function selectAllApplication(ctrlid) {
        var gr = $('#cmbDelApp' + ctrlid).combogrid('grid');
        if ($('#cmbClientAction' + ctrlid).val() == "Delete")
            gr.datagrid('selectAll');
        else
            gr.datagrid('unselectAll');
    }
    function formatDate(value) {
        if (value == null)
            return '';
        var date = new Date(value);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var month = '';
        switch (m) {
            case 1:
                month = 'Jan';
                break;
            case 2:
                month = 'Feb';
                break;
            case 3:
                month = 'Mar';
                break;
            case 4:
                month = 'Apr';
                break;
            case 5:
                month = 'May';
                break;
            case 6:
                month = 'Jun';
            case 7:
                month = 'Jul';
                break;
            case 8:
                month = 'Aug';
                break;
            case 9:
                month = 'Sep';
                break;
            case 10:
                month = 'Oct';
                break;
            case 11:
                month = 'Nov';
                break;
            case 12:
                month = 'Dec';
                break;
        }
        var d = date.getDate();
        return (d < 10 ? ('0' + d) : d) + ' ' + month + ' ' + y;
    }
    function getAppData(ctrlid) {
        var appid = $('#cmbViewApp' + ctrlid).val();
        $.ajax({
            url: '/webservices/applicationcontact.ashx?method=SelectApplicationByAppID&app_id=' + appid,
            success: function (data) {
                $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                    $('#lblDate' + ctrlid).html(formatDate(rec.CreatedDate));
                    $('#lblloanAmt' + ctrlid).html(rec.DesiredAmount);
                    $('#lblSecurity' + ctrlid).html(rec.Security);
                });
            }
        });
    }
    $(document).ready(function () {
        $('#pnlCompareDuplicate').panel('resize', {
            width: window.innerWidth,
            height: window.innerHeight
        });
        $('#dgCompareDuplicate').datagrid('resize', {
            width: window.innerWidth - 10
        });
        if (currentClientID != '') {
            $.ajax({
                url: '/WebServices/ApplicationContact.ashx?method=ApplicationContactSelect&ContactID=' + currentClientID,
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {

                        $.ajax({
                            url: '/WebServices/DuplicateContactDetective.ashx?method=PrepareDataGrid',
                            data: {
                                'ContactID': currentClientID, 'FirstName': rec.FirstName, 'SurName': rec.SurName, 'DateBirth': rec.DateBirth, 'EMail': rec.Email,'secondEmailAddress':rec.secondEmailAddress, 'Mobile': rec.Mobile, 'Street': rec.Street, 'State': rec.State, 'Suburb': rec.Suburb
                            },
                            success: function (respons) {
                                if (respons == "0") {
                                    document.getElementById("p1").innerHTML = " <span style=\"color:red;font-size:16px;\"> Large number of Duplicate Client found </span>";
                                }
                                else {
                                    document.getElementById("customdg").innerHTML = respons;
                                    $('#p1').hide();
                                    $('#lnkSave').addClass("easyui-linkbutton l-btn");
                                    var inputsCombo = document.getElementsByTagName("select");
                                    for (x = 0; x <= inputsCombo.length - 1; x++) {
                                        myname = inputsCombo[x].getAttribute('id');
                                        if (myname.indexOf("cmbDelApp") == 0) {
                                            $('#hdnClientID').val(myname.replace('cmbDelApp', ''));
                                            getAppData($('#hdnClientID').val());
                                            $('#' + myname).combogrid({
                                                panelWidth: 150,
                                                multiple: true,
                                                idField: 'app_id',
                                                textField: 'app_id',
                                                editable: true,
                                                url: '/WebServices/ApplicationContact.ashx?method=GetApplicationForClient&ContactID=' + $('#hdnClientID').val(),
                                                columns: [[
                                                    { field: 'ck', checkbox: true },
                                                    { field: 'app_id', width: 80 },
                                                ]],
                                                fitColumns: true
                                            });
                                        }
                                    }
                                  
                                }
                            }
                        });
                    });
                }
            });
        }
        else
            $.messager.alert('Morgan CRM', 'Invalid Data', 'error');
    });
</script>
<body>
    <form id="form1" runat="server">
        <div id="pnlCompareDuplicate" class="easyui-panel" style="width: auto; height: 450px" title="Automatic Detective Duplicate Client">
            
            <input type="hidden" runat="server" id="hdnUserName" />
            <div id="customdg" style="width: auto; height: auto">
            </div>
            <div id="p1" style="width: 100%; height: auto; text-align: center; margin-top: 100px">
                <img src="../../Media/progress.gif" style="animation: ease-in-out" />
                <br />
                <b>Please wait... </b>
            </div>
            <div id="dgfooter" class="fitem" style="width: 100%; text-align: center">
                <input id="hdnClientID" type="hidden" />
            </div>
        </div>
    </form>
</body>
</html>
